package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.atguigu.gulimall.product.vo.webvo.SkuItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    AttrDao attrDao;

    @Autowired
    AttrServiceImpl attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryIdPage(Map<String, Object> params, Long catelogId) {
        //三级分类id==0,查所有
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<AttrGroupEntity>();
        //null
        if (catelogId == 0){
            return query(params,queryWrapper);
        }{
            //catelogId != 0 代表是点击三级菜单直接查询,并且也可以根据条件查询
            queryWrapper.eq("catelog_Id", catelogId);
            return query(params,queryWrapper);
        }
    }

    //删除关联属性，可批量删除
    @Override
    public void deleteRelation(AttrGroupRelationVo[] relationVos) {
        List<AttrGroupRelationVo> voList = Arrays.asList(relationVos);
        List<AttrAttrgroupRelationEntity> collect = voList.stream().map((vo) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(vo, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteRelationBatch(collect);
    }

    /*
        获取分类下所有分组&关联属性
        1.cat_log: 225
        2.attr_group_id: 1，2，7，8
        3.attr_group_id=1 -> attr_id=8，7
          attr_group_id=2...
     */
    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrs(Long catelogId) {
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<AttrGroupWithAttrsVo> collect = attrGroupEntities.stream().map(attrGroupEntity -> {
            AttrGroupWithAttrsVo withAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrGroupEntity, withAttrsVo);
//            List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupEntity.getAttrGroupId()));

            //方式1
            List<AttrEntity> attrs = attrService.getRelationAttr(attrGroupEntity.getAttrGroupId());
            withAttrsVo.setAttrs(attrs);

            //方式2
//            List<AttrEntity> attrs = relationEntities.stream().map(relation -> {
//                AttrEntity attrEntities = attrDao.selectOne(new QueryWrapper<AttrEntity>().eq("attr_id", relation.getAttrId()));
//                return attrEntities;
//            }).collect(Collectors.toList());

            //方式3
//            List<Long> attrIds = relationEntities.stream().map(relation -> {
//                return relation.getAttrId();
//            }).collect(Collectors.toList());
//            //这里一定要判空，否则mybtais-plus查询时会报错
//            if (attrIds != null && attrIds.size() > 0){
//                //? bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException:
//                //You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 3
//                List<AttrEntity> attrEntities = attrDao.selectList(new QueryWrapper<AttrEntity>().in("attr_id", attrIds));
//                withAttrsVo.setAttrs(attrEntities);
//            }
            return withAttrsVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<SkuItemVo.SkuItemSaleAttrVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        AttrGroupDao baseMapper = this.baseMapper;
        List<SkuItemVo.SkuItemSaleAttrVo> list = baseMapper.getAttrGroupWithAttrsBySpuId(catalogId,spuId);
        return list;
    }


    //如果检索条件key不为空
    //select * from xxx where catelog_Id = 'catelogId' and (attr_group_id = 'key' or attr_group_name like %key%);
    public PageUtils query(Map<String, Object> params,QueryWrapper<AttrGroupEntity> queryWrapper){
        String key = (String) params.get("key");
        queryWrapper.and(!StringUtils.isEmpty(key),(obj)->{
            obj.eq("attr_group_id",key).or().like("attr_group_name",key);
        });
        IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),queryWrapper);
        return new PageUtils(page);
    }



}